package com.pagoda.nerp.trade.app.quality.timer;

import com.alibaba.fastjson.JSONObject;
import com.pagoda.nerp.trade.app.quality.utils.InvokeQualityPartUtils;
import com.pagoda.nerp.trade.common.ConstantDefine;
import com.pagoda.nerp.trade.common.enums.ErrorCodeMappingEnums;
import com.pagoda.nerp.trade.common.exception.BaseException;
import com.pagoda.nerp.trade.common.objectutil.PropertyConfigurer;
import com.pagoda.nerp.trade.common.wx.handler.WxMessageHandler;
import com.pagoda.nerp.trade.dao.MdAccountDao;
import com.pagoda.nerp.trade.dao.MdFeedbackDao;
import com.pagoda.nerp.trade.dao.MdQualityRecordDao;
import com.pagoda.nerp.trade.entity.MdFeedback;
import com.pagoda.nerp.trade.entity.MdQualityRecord;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by dell on 2016/12/27.
 */
@Component
public class QueryApplyResult extends QuartzJobBean {

    private final org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MdQualityRecordDao qualityRecordDao;
    @Autowired
    private MdFeedbackDao feedbackDao;
    @Autowired
    private MdAccountDao accountDao;

    /**
     * 定时器任务: 每10分钟调用质检平台接口查询一次质检申请状态为E(申请审核中）的质检记录的申请结果
     * @param jobExecutionContext
     * @throws JobExecutionException
     */
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        List<MdQualityRecord> qualityRecordList = qualityRecordDao.queryQualityRecordListByStatus(ConstantDefine.QUALITY_STATUS_APPLY_VERIFY);
        if (qualityRecordList == null) {
            return;
        }

        Map<String, String> paramMap = new HashMap<String, String>();

        for (MdQualityRecord temp : qualityRecordList) {
            paramMap.put("code", temp.getQualityPlatId());

            //调用质检平台接口： 查询质检申请结果
            JSONObject jsonObject = InvokeQualityPartUtils.invokeQualityPart(paramMap, PropertyConfigurer.parseStr("quality.apply.result.url"));
            if ((Integer)jsonObject.get("code") != 0) {
                logger.error("QueryApplyResult --> executeInternal:Invoke quality part failed!code="+jsonObject.get("code"));
                continue;
            }

            JSONObject dataJson = jsonObject.getJSONObject("data");

            MdQualityRecord qualityRecord = new MdQualityRecord();
            if (dataJson.getIntValue("reply_status") == 2) {
                //失败 --->申请失败
                qualityRecord.setStatus(ConstantDefine.QUALITY_STATUS_APPlY_FAILED);
            } else if (dataJson.getIntValue("reply_status") == 1) {
                //成功--> 等待质检
                qualityRecord.setStatus(ConstantDefine.QUALITY_STATUS_WAIT_TEST);
            } else {
                //暂时没有申请结果
                continue;
            }

            //修改状态
            qualityRecord.setQualityRecordId(temp.getQualityRecordId());
            int i = qualityRecordDao.updateByPrimaryKey(qualityRecord);
            if (i < 0) {
                logger.error("QueryApplyResult --> executeInternal: failed to update quality record status !");
                throw new BaseException(ErrorCodeMappingEnums.ERROR_EXCEPTION_DB_DML);
            }

            //回写反馈信息
            MdFeedback feedback = new MdFeedback();
            feedback.setQualityRecordId(temp.getQualityRecordId());
            feedback.setQualityType( dataJson.getString("qc_type"));
            feedback.setTestOrgCode( dataJson.getString("delivery_center_code"));
            feedback.setTestOrgName( dataJson.getString("delivery_center_name"));
            feedback.setPrice((long) dataJson.getIntValue("offer_price"));
            feedback.setPhoneNumber( dataJson.getString("inspector_tel"));
            feedback.setTestUser( dataJson.getString("inspector"));
            feedback.setRemark( dataJson.getString("remark"));
            i = feedbackDao.insert(feedback);
            if (i < 0) {
                logger.error("QueryApplyResult --> executeInternal:Failed to insert MdFeedback! feedback=" + feedback.toString());
                continue;
            }

            //查询供应商对应的有openid的子账户
            List<String> openIdList = accountDao.selectOpenIdByVendorId(temp.getVendorId());
            if (openIdList == null || openIdList.size() == 0) {
                continue;
            }

            //组装模板信息
            String first = "您发布的质检需求收到一条新的回复信息，请登录百果园交易平台查看详情。";
            String publish = "百果园";
            String datetime = new SimpleDateFormat("yyyy-MM-dd").format(new Timestamp(System.currentTimeMillis()));
            for (String tempOpenId : openIdList) {
                WxMessageHandler.sendInfoPublishNotifyMsg(first, publish, "", datetime, "", tempOpenId);
            }
        }
    }

}
